package cn.intotw.rdcj.core.config;

import cn.intotw.rdcj.core.bean.DataResponse;
import cn.intotw.rdcj.core.constant.Constants;
import cn.intotw.rdcj.core.constant.PubECDef;
import cn.intotw.rdcj.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;


@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ModelAndView defaultErrorHandler(MethodArgumentNotValidException e) {
        //valid bind校验的异常
        log.info("参数校验不通过:{}",e.getParameter().getParameterName());
        BindingResult bindingResult = e.getBindingResult();
        return new ModelAndView(Constants.JSON_DATA_VIEW, DataResponse.failure(PubECDef.EC_SYS_VALID_ERROR, bindingResult.getFieldError().getDefaultMessage()));
    }

    @ExceptionHandler(value = BusinessException.class)
    public ModelAndView businessExceptionHandler(BusinessException e) {
        //业务异常
        log.info("业务异常：", e);
        return new ModelAndView(Constants.JSON_DATA_VIEW, DataResponse.failure(e.getCode(), e.getBizMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e) {
        log.error("系统异常：", e);
        return new ModelAndView(Constants.JSON_DATA_VIEW, DataResponse.failure(PubECDef.EC_SYS_ERROR, PubECDef.EC_SYS_ERROR_DESC));
    }
    @ExceptionHandler(value = ServletRequestBindingException.class)
    public ModelAndView handlerHeaderException(ServletRequestBindingException e) {

        log.error("参数一样：", e);

        return new ModelAndView(Constants.JSON_DATA_VIEW, DataResponse.failure(PubECDef.EC_SYS_VALID_ERROR, e.getMessage()));
    }
}
